package com.sayice.robotconflict.model

import com.sayice.robotconflict.util.GSON
import com.sayice.robotconflict.util.toBean

/**
 * 游戏服务端与客户端的通信消息
 *
 * @author shubing
 */
data class Message(
    /**
     * 消息类型
     */
    val type: String,

    /**
     * 操作
     */
    val action: String? = null,

    /**
     * 数据
     */
    val data: Any? = null
) {
    /**
     * 获取数据为 Bean
     */
    inline fun <reified T> dataAsBean(): T =
        @Suppress("UNCHECKED_CAST") (data as Map<String, *>).toBean<T>()

    /**
     * 获取数据为 Bean列表
     */
    inline fun <reified T> dataAsBeanList(): List<T> =
        @Suppress("UNCHECKED_CAST") (data as List<Map<String, *>>).map { it.toBean() }

    fun toJson(): String = GSON.toJson(this)
}